"""   Copyright 2011 Bart Enkelaar

   Licensed under the Apache License, Version 2.0 (the "License");
   you may not use this file except in compliance with the License.
   You may obtain a copy of the License at

       http://www.apache.org/licenses/LICENSE-2.0

   Unless required by applicable law or agreed to in writing, software
   distributed under the License is distributed on an "AS IS" BASIS,
   WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
   See the License for the specific language governing permissions and
   limitations under the License.
"""

from google.appengine.dist import use_library
use_library('django', '1.2')

from google.appengine.ext import webapp
from google.appengine.ext.webapp import template
from google.appengine.ext.webapp.util import run_wsgi_app
from lyricbuilder import SongBuilder
import cgi
import logging
import os

ANALYTICS_VAR = {"google_analytics": r"""
<script type=\"text/javascript\">

  var _gaq = _gaq || [];
  _gaq.push(['_setAccount', 'UA-5224564-2']);
  _gaq.push(['_trackPageview']);

  (function() {
    var ga = document.createElement('script'); ga.type = 'text/javascript'; ga.async = true;
    ga.src = ('https:' == document.location.protocol ? 'https://ssl' : 'http://www') + '.google-analytics.com/ga.js';
    var s = document.getElementsByTagName('script')[0]; s.parentNode.insertBefore(ga, s);
  })();
</script>
"""}

class MainPage(webapp.RequestHandler):
    def get(self):
        logging.debug("Received request: '%s'" % self.request)
        path = os.path.join(os.path.dirname(__file__), 'index.html')
        self.response.out.write(template.render(path, ANALYTICS_VAR))

class CallBack(webapp.RequestHandler):
    def get(self):
        logging.debug("Received request: '%s'" % self.request)
        self.response.out.write("Callback received: %s" % self.request)

class CreateLyrics(webapp.RequestHandler):
    def post(self):
        logging.debug("Received request: '%s'" % self.request)
        path = os.path.join(os.path.dirname(__file__), 'song.html')
        subject = cgi.escape(self.request.get('subject')) #@UndefinedVariable
        logging.debug("Building a song with the subject: '%s'" % subject)
        song = SongBuilder(subject, line_limit=70, page_step=1).create() # This is where the magic happens.
        if song:
            logging.info("Created a song about '%s', with %s chorus lines and %s verse lines" %
                        (subject, len(song.chorus_lines), len(song.verse_lines)))
        else:
            logging.warning("No song could be created for subject %s" % subject)
        subtitle = (self._capitalize(song.chorus_lines[0].lineOne.sentence)
                    if song and song.chorus_lines else "Utter Nothingness...")
        self.response.out.write(template.render(path, join_dicts(ANALYTICS_VAR, {"subject": subject,
                                                       "subtitle": subtitle,
                                                       "lines": self._generate_lines(song) if song else []})))
    
    def _generate_lines(self, song):
        result = []
        a = song.lines_per_verse
        result += self._create_block(song.chorus_lines)
        for i in range(0, song.verses):
            result += self._create_block(song.verse_lines[i * a : (i + 1) * a])
            result += self._create_block(song.chorus_lines)
        result += self._create_block(song.chorus_lines)
        return result

    def _capitalize(self, line):
        if len(line) < 2:
            return line.upper()
        return line[0].upper() + line[1:]

    def _create_block(self, lines):
        result = []
        for line in lines:
            result.append(self._capitalize(line.lineOne.sentence))
            result.append(self._capitalize(line.lineTwo.sentence))
        result += ["&nbsp;"]
        return result
    
def join_dicts(dictOne, dictTwo):
    result = {}
    for k, v in dictOne.iteritems():
        result[k] = v
    for k, v in dictTwo.iteritems():
        result[k] = v
    return result
    
application = webapp.WSGIApplication([('/', MainPage),
                                      ('/search', CreateLyrics),
                                      ('/callback', CallBack)], debug=True)

def main():
    run_wsgi_app(application)

if __name__ == "__main__":
    main()
